var express = require('express');
var router = express.Router();
var db = require('../db.js');

/* GET users listing. */
// add
router.all('/add',function(req,res){
  if(req.method=="POST"){
    var reqData=req.body;
  }else{
    var reqData=req.query||req.params
  }
  console.log(reqData)
  db.User.find(reqData.userQuery).then(function(userData){
    if(userData.statu!="baned"){
      reqData.topicQuery.statu={"$ne":"baned"};
      db.Topic.find(reqData.topicQuery).then(function(topicData){
        // console.log('topicData:',topicData)
        if(topicData.length>0){
          if(topicData[0].type=="free"){
            reqData.noteQuery.author_id=userData[0]._id;
            reqData.noteQuery.topic_id=topicData[0]._id;
            reqData.noteQuery.author_name=userData[0].name;
            reqData.noteQuery.topic_name=topicData[0].name;
            console.log('noteQuery', reqData.noteQuery)
            var newNote=new db.Note(reqData.noteQuery)
            newNote.save().then(function(){
              db.Note.find({topic_id:topicData[0]._id}).then(function(sameTopicData){
                // console.log(sameTopicData)
                var topic={}
                topic.note_count=sameTopicData.length;
                sameTopicData=sameTopicData.filter(function(item){
                  if(item.tar_id=="0000"){
                    return item
                  }
                })
                topic.p0000_count=sameTopicData.length;
                console.log('noyejs 36',topic);
                db.Topic.findOneAndUpdate({_id:topicData[0]._id},topic).then(function(){
                  res.json({
                    code:200,
                    msg:'发表成功'
                  })
                })
              })
            })
          }else if(topicData[0].type=="personal"){
            if(userData[0]._id==topicData[0].creater_id||reqData.noteQuery.tar_id!="0000"){
              reqData.noteQuery.author_id=userData[0]._id;
              reqData.noteQuery.topic_id=topicData[0]._id;
              reqData.noteQuery.author_name=userData[0].name;
              reqData.noteQuery.topic_name=topicData[0].name;
              var newNote=new db.Note(reqData.noteQuery)
              newNote.save().then(function(){
              })
            }else{
              res.json({
                code:1003,
                msg:'你无权此发帖'
              })
            }
          }
        }else{
          res.json({
            code:1004,
            msg:'话题不存在'
          })
        }
        if(userData.length>0){
          
        }else{
          res.json({
            code:1004,
            msg:'话题不存在'
          })
        }
      })
    }else{
      res.json({
        code:1002,
        msg:'账户被封禁'
      })
    }
  })
})
router.all('/updata',function(req,res){
  if(req.method=="POST"){
    var reqData=req.body;
  }else{
    var reqData=req.query||req.params
  }
  console.log('notejs 92',reqData)
  db.Note.findOneAndUpdate(reqData.query,reqData.data).then(function(data){
    res.json({
      code:200,
      msg:'提交成功',
      data
    })
  })
})
router.all('/query', function (req, res) {
  if (req.method == "POST") {
    var reqData = req.body;
  } else {
    var reqData = req.query || req.params;
  }
  var pageNum=reqData.pageNum*1||1;
  var pageSize=reqData.pageSize*1||20;
  if(!!reqData.query&&!!reqData.query.$reg){
    for (const key in reqData.query.$reg) {
      if (reqData.query.hasOwnProperty(key)) {
        reqData.query[key]=new RegExp(reqData.query[key],'i')    
      }
    }
    delete reqData.query.$reg;
  }
  console.log('notejs 116',reqData.query)  
  db.Note.find(reqData.query||{}).then(function(data){
    var pageCount=Math.ceil(data.length/pageSize);
    pageNum=pageNum>pageCount?pageCount:pageNum;
      console.log('notejs 113')    
      // pageNum=pageNum==0?0:pageNum-1;
    // console.log((pageNum==0?0:pageNum-1)*pageSize)
    db.Note.find(reqData.query||{}).sort({'_id':-1}).skip((pageNum==0?0:pageNum-1)*pageSize).limit(pageSize).then(function(data){
      res.json({
        code:200,
        pageNum:pageNum,
        pageSize,
        pageCount,
        data
      })
    })
  })
})
router.all('/fuzzy', function (req, res) {
  if (req.method == "POST") {
    var reqData = req.body;
  } else {
    var reqData = req.query || req.params;
  }
  db.Note.find({ name: { $regex: reqData.query.name }, statu:{"$ne":"baned"}}).then(function(data){
    res.json({ 
      code:200,
      data: data 
    })
  })
})


// router.post('/add/:bid/:user', (req, res) => {
//   var b_id = req.params.bid;
//   var user = req.params.user;
//   db.User.find({ name: user, statu: "normal" }).then(function (data) {
//     if (data[0].statu != "normal") {
//       res.json({
//         code: 'error',
//         msg: '发布失败，您已被封禁'
//       })
//     }
//     if (req.body.title.trim() == "") {
//       req.body.title = req.body.content.slice(0, 20);
//     }
//     var note = new db.Note({
//       title: req.body.title,
//       author: data[0]._id,
//       community: b_id,
//       statu: 'normal',
//       content: req.body.content,
//       ans: [],
//       date: Date.now()
//     })
//     note.save().then(function () {
//       res.json({
//         code: 'success',
//         msg: '发布成功！！'
//       })
//     })
//   })
// })
// router.post('/ans/:nid/:user', (req, res) => {
//   var n_id = req.params.nid;
//   var user = req.params.user;
//   db.User.find({ name: user, statu: "normal" }).then(function (data) {
//     var u_id = data[0]._id;
//     db.Note.find({ _id: n_id }).then(function (note) {
//       var tempNote = note[0];
//       tempNote.ans.push({
//         author: u_id,
//         targetAuthor: req.body.targetAuthor,
//         targetId: req.body.targetId,
//         content: req.body.content,
//         _id: Math.random(Number(Date.now()))
//       })
//       db.Note.findByIdAndUpdate({ _id: n_id }, tempNote).then((data) => {
//         res.json({
//           code: 'success',
//           msg: '发布成功！！'
//         })
//       })
//     })
//   })
// })
module.exports = router;